<template>
  <BKModal
    v-model="visible"
    :width="modalQueryConfigKeyMap[layId] ? modalQueryConfigKeyMap[layId].width :500"
    height="500"
    :show-zoom="false"
    :title="title"
    class="ysqxx-modal"
    transfer
  >
    <div class="full-box p-l-mini p-t-mini">
      <ConfigGrid
        ref="grid"
        class="ysqxx-table right-table-toolbar"
        border="none"
        :stripe="false"
        :has-seq="false"
        :has-toolbar-left="true"
        :highlight-current-row="true"
        :has-add="false"
        :has-batch-remove="false"
        :has-checkbox="false"
        :toolbar-config="null"
        :configs="configs"
      >
        <template
          #toolbarLeftAppend
        >
          <div
            class="flex-ai-c"
          >
            <BKForm
              ref="form"
              class="ysqxx-form"
              :items="modalQueryConfigKeyMap[layId] ? modalQueryConfigKeyMap[layId].formItems:[]"
              :has-reset="false"
              :has-submit="false"
              label-width="80px"
              size="mini"
              inline
            >
              <template
                #ADDVCD
              >
                <el-cascader
                  v-model="ADDVCD"
                  class="blue-select"
                  placeholder="请选择"
                  :options="allAdminAreas"
                  popper-class="blue-select-dropdown"
                  :props="{ checkStrictly: true }"
                  :show-all-levels="false"
                  @change="handleFormDataChange"
                  filterable
                  clearable
                />
              </template>
            </BKForm>
          </div>
        </template>
      </ConfigGrid>
    </div>
  </BKModal>
</template>

<script>
import { szLayerId, swswLayerId, sqLayerId, dxsLayerId } from '../../variable'
import { mapState } from 'vuex'
import { debounce } from 'throttle-debounce'
const pickerOptions = {
  disabledDate (time) {
    return time.getTime() > Date.now()
  }
}
export default {
  name: 'SwswModal',
  data () {
    return {
      szLayerId,
      swswLayerId,
      sqLayerId,
      dxsLayerId,
      visible: false,
      title: '',
      configs: {},
      ADDVCD: [],
      layId: '',
      chartData: null,
      allAdminAreas: []
    }
  },
  computed: {
    ...mapState('ysqxx', ['adminAreas', 'stationTypeList', 'watershedZones']),
    modalQueryConfigKeyMap () {
      return {
        ysqxx_SZ: {
          title: '水质站',
          width: 667,
          config: {
            isView: false,
            noOperation: true,
            noParentParam: true,
            appId: 'YSJC',
            bzCode: 'YSJC',
            metaSet: 'YSQJC_WQ_WATER_QUALITY_FC',
            gridMethod: 'select_SZFC',
            defaultQueryParamsProcessor: this.swDefaultQueryParamsProcessor

          },
          formItems: [
            {
              type: 'select',
              label: '水质类别',
              field: 'SZLB',
              props: { dictionaryKey: 'YSJC_WQ_TYPE', clearable: true, class: 'blue-select', popperClass: 'blue-select-dropdown' },
              events: {
                change: this.debounceHandleFormDataChange
              }
            },
            {
              type: 'select',
              label: '时间类别',
              field: 'SFNOW',
              props: {
                clearable: true,
                class: 'blue-select',
                popperClass: 'blue-select-dropdown',
                mock: [{ label: '当前日期', value: 'NOW' }, { label: '去年同期', value: 'LAST' }]
              },
              events: {
                change: this.debounceHandleFormDataChange
              }
            },
            {
              type: 'date-picker',
              label: '时间',
              field: 'SEARCH_TIME',
              labelWidth: '60px',
              required: true,
              props: { class: 'blue-select blue-date-picker', clearable: false, type: 'month', pickerOptions: pickerOptions, popperClass: 'blue-select-dropdown' },
              events: {
                change: this.debounceHandleFormDataChange
              }
            }
          ]
        },
        ysqxx_SWSW: {
          title: '水文水位站',
          width: 1000,
          config: {
            isView: false,
            noOperation: true,
            noParentParam: true,
            appId: 'YSJC',
            bzCode: 'YSJC',
            metaSet: 'YSQJC_ST_STBPRP_B_FC',
            gridMethod: 'select_stationByXzq',
            defaultQueryParamsProcessor: this.swDefaultQueryParamsProcessor
          },
          formItems: [
            {
              type: 'select',
              label: '站类',
              field: 'STTP',
              props: { mock: this.stationTypeList, clearable: true, class: 'blue-select', popperClass: 'blue-select-dropdown' },
              events: {
                change: this.debounceHandleFormDataChange
              }
            },
            {
              type: 'select',
              label: '流域分区',
              field: 'BSNM',
              props: { mock: this.watershedZones, clearable: true, class: 'blue-select', popperClass: 'blue-select-dropdown' },
              events: {
                change: this.debounceHandleFormDataChange
              }
            },
            { type: 'input', label: '行政区划', field: 'ADDVCD', slot: 'ADDVCD' }
          ]
        },
        ysqxx_SQ: {
          title: '墒情站',
          width: 1000,
          config: {
            isView: false,
            noOperation: true,
            noParentParam: true,
            appId: 'YSJC',
            bzCode: 'YSJC',
            metaSet: 'YSQJC_ST_STBPRP_B_SQZ_FC',
            gridMethod: 'select_stationByXzq',
            defaultQueryParamsProcessor: this.swDefaultQueryParamsProcessor
          },
          formItems: [
            {
              type: 'select',
              label: '流域分区',
              field: 'BSNM',
              props: {
                mock: this.watershedZones,
                clearable: true,
                class: 'blue-select',
                popperClass: 'blue-select-dropdown'
              },
              events: {
                change: this.debounceHandleFormDataChange
              }
            },
            { type: 'input', label: '行政区划', field: 'ADDVCD', slot: 'ADDVCD' }
          ]
        },
        ysqxx_DXS: {
          title: '地下水站',
          width: 876,
          config: {
            isView: false,
            noOperation: true,
            noParentParam: true,
            appId: 'YSJC',
            bzCode: 'YSJC',
            metaSet: 'YSQJC_UW_ZDJBXX_FC',
            gridMethod: 'get_stcdFC',
            defaultQueryParamsProcessor: this.swDefaultQueryParamsProcessor
          },
          formItems: [
            {
              type: 'select',
              label: '行政区划',
              field: 'CITY',
              props: { mock: this.adminAreas[0]?.children || [], class: 'blue-select', clearable: true, popperClass: 'blue-select-dropdown' },
              events: {
                change: this.debounceHandleFormDataChange
              }
            },
            {
              type: 'date-picker',
              label: '时间',
              field: 'SEARCH_TIME',
              labelWidth: '60px',
              required: true,
              props: { class: 'blue-select blue-date-picker', clearable: false, type: 'month', pickerOptions: pickerOptions, popperClass: 'blue-select-dropdown' },
              events: {
                change: this.debounceHandleFormDataChange
              }
            }
          ]
        }
      }
    }
  },
  created () {
    this.debounceHandleFormDataChange = debounce(300, this.handleFormDataChange)
  },
  mounted () {
  },
  methods: {
    async openModal ({ params, chartData, layId }) {
      this.visible = true
      this.layId = layId
      this.chartData = chartData
      this.configs = this.modalQueryConfigKeyMap[layId].config
      this.title = this.modalQueryConfigKeyMap[layId].title
      if (this.layId === this.swswLayerId || this.layId === this.sqLayerId) {
        await this.fetchAdminAreas()
        this.ADDVCD = this.getAreaPathById(this.allAdminAreas, this.chartData.xzqdm) ?? ['130000', this.chartData.xzqdm]
      }
      this.$nextTick(() => {
        this.$refs.form.setFormData(params)
        this.$refs.grid.refresh()
      })
    },
    async  fetchAdminAreas () {
      const rows = await this.$utils.dictionary.getOptionsByKey('YSQJC_JC_XZQ')
      this.allAdminAreas = this.listToTree('ROOT', rows)
    },
    listToTree (id, rows) {
      const arr = rows.filter(item => item.fcode === id)
      if (!arr.length) return null
      return arr.map(item => ({
        label: item.label,
        value: item.value,
        children: this.listToTree(item.value, rows)
      }))
    },
    swDefaultQueryParamsProcessor (params) {
      const tempMethodParams = JSON.parse(params.methodParams)
      const filterParam = {}
      tempMethodParams.columnFilterParam.forEach(ele => {
        filterParam[ele.field] = ele.conditions[0].value ? ele.conditions[0].value : ele.conditions[1].value
      })
      const formData = this.$refs.form.getFormData()
      console.log({ ADDVCD: this.ADDVCD })
      const obj = (this.layId === this.szLayerId || this.layId === this.dxsLayerId) ? formData
        : {
          ...formData,
          ADDVCD: (this.ADDVCD && this.ADDVCD.length) ? this.ADDVCD[this.ADDVCD.length - 1] : '130000'
        }
      const methodParams = {
        ...obj,
        ...filterParam
      }
      params.methodParams = JSON.stringify(methodParams)
      console.log({ methodParams, tempMethodParams })
      return params
    },
    getAreaPathById (tree, id, path) {
      tree = Array.isArray(tree) ? tree : [tree]
      if (!path) {
        path = []
      }
      for (let i = 0, len = tree.length; i < len; i++) {
        const tempPath = [...path]
        tempPath.push(tree[i].value)
        if (tree[i].value === id) {
          return tempPath
        }
        if (tree[i].children) {
          return this.getAreaPathById(tree[i].children, id, tempPath)
        }
      }
    },
    handleFormDataChange () {
    //  const formData = this.$refs.form.getFormData()
      this.$nextTick(() => {
        this.$refs.grid.refresh()
      })
    }

  }
}
</script>
<style lang="scss" scoped>
::v-deep.ysqxx-form .blue-select,
.blue-select {
  width: 120px !important;
}

::v-deep.ysqxx-table.right-table-toolbar {
  .toolbar-left-container {
    padding-right: 8px;
    justify-content: flex-end;
    display: flex;
    align-items: center;
  }
}
</style>
